package com.lingx.utils;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.lingx.bean.TokenBean;

public class TokenUtils {
	private static Cache<String, TokenBean> TOKEN_CACHE=null;
	//过期时间设置(30分钟)
    private static final long EXPIRE_TIME = 30*60*1000;

    //私钥设置
    private static final String TOKEN_SECRET = Utils.getRandomString(32);
    
    public static String getToken(TokenBean token) {
    	return getToken(token,EXPIRE_TIME);
    }
    
    public static void logout(String account) {
    	String token=null;
    	if(TOKEN_CACHE==null)return;
    	Map<String,TokenBean>map=TOKEN_CACHE.asMap();
    	for(String key:map.keySet()) {
    		TokenBean bean=map.get(key);
    		if(bean.getAccount().equals(account)) {
    			token=key;break;
    		}
    	}
    	if(token!=null)TOKEN_CACHE.invalidate(token);
    }
    
    public static String getToken(TokenBean tokenBean,long time){
    	
    	String token=TOKEN_SECRET+UUID.randomUUID().toString().replaceAll("-", "");
    	if(TOKEN_CACHE==null) {
    		//System.out.println("有效时间:"+time/1000/60);
    		TOKEN_CACHE=CacheBuilder.newBuilder().maximumSize(100000).expireAfterAccess(time/1000/60, TimeUnit.MINUTES).build();
    	}
    	TOKEN_CACHE.put(token, tokenBean);

        return token;

    }

    public static TokenBean getTokenData(String token){
        return TOKEN_CACHE.getIfPresent(token);
    }

    public static String creatToken(String userId,String userName,String orgIds,String roleIds){
        //这里是传入的是token对象，决定token的内容
    	TokenBean tk=new TokenBean();
    	tk.setUserId(userId);
    	tk.setUserName(userName);
    	tk.setOrgIds(orgIds);
    	tk.setRoleIds(roleIds);
    	tk.setLastLoginTime(System.currentTimeMillis());
		//交给上面的实现类得到token
        return getToken(tk);
    }

    public static boolean verifyToken(String token) {
    	if(TOKEN_CACHE==null)return false;
    	return TOKEN_CACHE.getIfPresent(token)!=null;
    }
    
    
    public static String getTokenDataUserId(String token){
    	if(TOKEN_CACHE==null||TOKEN_CACHE.getIfPresent(token)==null)return null;
        return TOKEN_CACHE.getIfPresent(token).getUserId();
    }
    
    public static void invalidate(String token) {
    	TOKEN_CACHE.invalidate(token);
    }
}
